<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-row>
        <!--<el-col :span="4.5">
          <el-form-item label="项目编号" prop="projectCode">
            <el-select v-model="queryParams.projectCode" filterable placeholder="请输入或选择项目编号" style="width: 200px;">
              <el-option
                  v-for="item in projectOptions"
                  :key="item"
                  :label="item"
                  :value="item"
              />
            </el-select>
          </el-form-item>
        </el-col>-->
        <!-- 下拉框+模糊搜索 -->
        <el-col :span="5">
          <el-form-item label="采购明细名称" prop="itemName" label-width="100px">
            <el-input
                v-model="queryParams.itemName"
                placeholder="请输入采购明细名称"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="4">
          <el-form-item label="创建人" prop="createBy">
            <el-input
                v-model="queryParams.createBy"
                placeholder="请输入创建人"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="创建时间">
            <el-date-picker
                v-model="daterangeCreateTime"
                value-format="YYYY-MM-DD"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="更新人" prop="updateBy">
            <el-input
                v-model="queryParams.updateBy"
                placeholder="请输入更新人"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="更新时间">
            <el-date-picker
                v-model="daterangeUpdateTime"
                value-format="YYYY-MM-DD"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:detail:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:detail:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:detail:remove']"
        >删除</el-button>
      </el-col>

      <!-- 导入 -->
      <el-col :span="1.5">
        <el-button
            type="info"
            plain
            icon="Upload"
            @click="handleImport"
            v-hasPermi="['system:detail:import']"
        >导入</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:detail:export']"
            v-if="false">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="detailList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column align="center" prop="id" v-if="false" />
      <el-table-column align="center" prop="areaId" v-if="false" />
      <el-table-column label="采购明细名称" align="center" prop="itemName" sortable :sort-method="nameSort"/>
      <el-table-column label="项目编号" align="center" prop="projectCode" v-if="false"/>
      <el-table-column label="合同额" align="center" prop="contractWithTax" sortable/>
      <el-table-column label="合同编号" align="center" prop="contractCode" sortable/>
      <el-table-column label="累计已发生成本（含税）" align="center" prop="realTotalWithTax" sortable/>
      <el-table-column label="实际进项税率" align="center" prop="taxRate" sortable>
        <template #default="scope">
          <span>{{ scope.row.taxRate * 100 }}%</span>
        </template>
      </el-table-column>
      <el-table-column label="已发生成本理论进项税额" align="center" prop="tax" sortable/>
      <el-table-column label="进度" align="center" prop="progress" sortable>
        <template #default="scope">
          <span>{{ (scope.row.progress * 100).toFixed(2) }}%</span>
        </template>
      </el-table-column>
      <el-table-column label="进度状态" align="center" prop="progressState" sortable>
        <template #default="scope">
          <dict-tag :options="progress_state" :value="scope.row.progressState"/>
        </template>
      </el-table-column>
      <el-table-column label="期数" align="center" prop="dateNumber" sortable/>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="创建人" align="center" prop="createBy" sortable v-if="false"/>
      <el-table-column label="创建时间" align="center" prop="createTime" sortable v-if="false"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:detail:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:detail:remove']">删除</el-button>
        </template>
      </el-table-column>
      <el-table-column label="施工借方发生额" align="center" prop="totalNoTax" v-if="false"/>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改明细对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="detailRef" :model="form" :rules="rules" style="width: 500px;">
        <el-form-item label="采购明细名称" prop="itemName" label-width="170px">
          <el-input v-model="form.itemName" placeholder="请输入采购明细名称" />
        </el-form-item>

        <!-- 下拉框+模糊搜索 -->
        <!--<el-form-item label="项目编号" prop="projectCode" label-width="170px">
          <el-input v-model="form.projectCode" readonly filterable placeholder="请输入或选择项目编号" style="width: 200px; background-color: #f2f2f2;">
          </el-input>
        </el-form-item>-->

        <el-form-item label="合同额" prop="contractWithTax" label-width="170px">
          <el-input v-model="form.contractWithTax" placeholder="合同额" />
        </el-form-item>

        <el-form-item label="合同编号" prop="contractWithTax" label-width="170px">
          <el-input v-model="form.contractCode" placeholder="合同编号" />
        </el-form-item>

        <el-form-item label="累计已发生成本（含税）" prop="realTotalWithTax" label-width="170px">
          <el-input v-model="form.realTotalWithTax" placeholder="请输入累计已发生的成本（含税）" />
        </el-form-item>

        <el-form-item label="实际进项税率" prop="taxRate" label-width="170px">
          <el-input v-model="form.taxRate" placeholder="请输入实际进项税率" />
        </el-form-item>

        <el-form-item label="供应商" prop="remark" label-width="170px">
          <el-input v-model="form.supplier" placeholder="请输入供应商" />
        </el-form-item>

        <el-form-item label="备注" prop="remark" label-width="170px">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 明细导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <div class="centered">
        <el-form-item label="期数选择" prop="dateNumber"  class="custom-label">
          <el-date-picker type="month"
                          v-model="upload.dateNumber"
                          format="YYYY-MM"
                          value-format="YYYY-MM"
                          :style="{width: '100%', fontSize: '18px'}"
                          placeholder="请选择期数"
                          clearable
                          style="width: 200px;">
          </el-date-picker>
        </el-form-item>
      </div>
      <el-upload
          ref="uploadRef"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '&dateNumber=' + upload.dateNumber"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag

      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">


            <!--<div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的 “材料采购明细”
            </div>-->
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Detail">

import { listDetail, getDetail, delDetail, addDetail, updateDetail } from "@/api/system/detail";
import { getToken } from "@/utils/auth";
import { ElDatePicker, ElButton } from 'element-plus';
const { proxy } = getCurrentInstance();
const { progress_state } = proxy.useDict('progress_state');

// 获取当前 URL 中的查询参数部分
const queryString = window.location.search;
// 使用 URLSearchParams 对象解析查询参数
const urlParams = new URLSearchParams(queryString);

const nameSort = (a, b) => {
  return a.itemName.localeCompare(b.itemName,'zh');
};
const remarkSort = (a, b) => {
  return a.remark.localeCompare(b.remark,'zh');
};

/*** 明细导入参数 */
const upload = reactive({
  // 是否显示弹出层（明细导入）
  open: false,
  // 弹出层标题（明细导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的明细数据
  updateSupport: 0,
  // 期数
  dateNumber: ref(getCurrentYearMonth()),
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/system/detail/importData?areaId=" + urlParams.get('areaId')
});
console.log(upload.url)
console.log("dateNumber: " + upload.dateNumber)

/** 导入按钮操作 */
function handleImport() {
  upload.title = "材料采购明细导入";
  upload.open = true;
};
/** 下载模板操作 */
function importTemplate() {
  proxy.download("system/detail/importTemplate", {
  }, `材料采购明细模板.xlsx`);
};
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>"
      + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getList();
};
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};
// 获取当前年月的函数
function getCurrentYearMonth() {
  const now = new Date();
  const year = now.getFullYear();
  const month = (now.getMonth() + 1).toString().padStart(2, '0'); // 补足月份的两位数
  return `${year}-${month}`;
}

const detailList = ref([]);
const projectOptions = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeCreateTime = ref([]);
const daterangeUpdateTime = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    itemName: null,
    projectCode: null,
    supplier: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    areaId: urlParams.get('areaId')
  },
  rules: {
    itemName: [
      { required: true, message: "采购项目名称不能为空", trigger: "blur" }
    ],
    dateNumber: [{
      required: true,
      message: '请选择期数',
      trigger: 'change'
    }],
  }
});

const { queryParams, form, rules } = toRefs(data);
console.log("this projectCode : " + form.value.projectCode)

/** 查询明细列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  queryParams.value.params["areaId"] = queryParams.value.areaId;
  console.log("areaId: " + queryParams.value.areaId);
  if (null != daterangeCreateTime && '' !== daterangeCreateTime) {
    queryParams.value.params["beginCreateTime"] = daterangeCreateTime.value[0];
    queryParams.value.params["endCreateTime"] = daterangeCreateTime.value[1];
  }
  if (null != daterangeUpdateTime && '' !== daterangeUpdateTime) {
    queryParams.value.params["beginUpdateTime"] = daterangeUpdateTime.value[0];
    queryParams.value.params["endUpdateTime"] = daterangeUpdateTime.value[1];
  }
  listDetail(queryParams.value).then(response => {
    detailList.value = response.dataList.rows;
    projectOptions.value = response.projectCodeList;
    total.value = response.dataList.total;
    console.log("total.value: ", response.dataList.total);
    loading.value = false;
  });
}
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    itemName: null,
    projectCode: null,
    realTotalWithTax: null,
    remark: null,
    supplier: null,
    tax: null,
    taxRate: null,
    totalNoTax: null,
    contractWithTax: null,
    contractCode: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("detailRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  daterangeCreateTime.value = [];
  daterangeUpdateTime.value = [];
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  form.value.areaId = queryParams.value.areaId;
  open.value = true;
  title.value = "添加明细";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getDetail(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改明细";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["detailRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateDetail(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDetail(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除明细编号为"' + _ids + '"的数据项？').then(function() {
    return delDetail(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/detail/export', {
    ...queryParams.value
  }, `detail_${new Date().getTime()}.xlsx`)
}

getList();
</script>
<style>
.centered {
  display: flex;
  justify-content: center;
}

.custom-label .el-form-item__label {
  font-size: 18px;
}
</style>
